package com.quan.common.biz.exception;

import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.quan.common.base.bean.ResultBean;
import com.quan.common.utils.WebUtils;

@RestControllerAdvice
public class ExceptionHandle {

	/**
	 * 字段验证异常统一处理
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public ResultBean validationErrorHandler(MethodArgumentNotValidException ex) {
		// 同样是获取BindingResult对象，然后获取其中的错误信息
		// 如果前面开启了fail_fast，事实上这里只会有一个信息
		// 如果没有，则可能又多个
		List<String> errorInformation = ex.getBindingResult()
				.getAllErrors().stream()
				.map(ObjectError::getDefaultMessage)
				.collect(Collectors.toList());

		return ResultBean.warning(errorInformation.toString());
	}
	
	/**
	 * 字段验证异常统一处理，使用 @Validated 标签
	 * https://blog.csdn.net/xuhuanfeng232/article/details/83894822
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(ConstraintViolationException.class)
	public ResultBean validationErrorHandler(ConstraintViolationException ex) {
	    List<String> errorInformation = ex.getConstraintViolations()
	            .stream()
	            .map(ConstraintViolation::getMessage)
	            .collect(Collectors.toList());
	    return ResultBean.warning(errorInformation.toString());
	}

	
	@ExceptionHandler(Exception.class)
	public @ResponseBody Object handleControllerException(HttpServletRequest request, HttpServletResponse response,
			Throwable e) {
		// 处理Ajax请求异常
		// 返回JSON格式数据
		return ResultBean.errorException(WebUtils.getStatus(request).value(), e.getMessage());
	}

}
